# -*- coding: utf-8 -*-


import os, re
from util import tool


class SongIrc(object):

    def __init__(self):
        super(SongIrc, self).__init__()
        self._blocks = {}

    def setUrl(self, url):
        """根据地址初始化歌词"""
        self.clear()
        if not os.path.exists(url):
            return
        with open(url, 'r') as f:
            irc_list = f.readlines()
            for line_irc in irc_list:
                arr = re.findall('\\[\\d{2}:\\d{2}\\.\\d{2,3}\\]', line_irc)
                arr_len = len(arr)
                if arr_len <= 0:
                    continue
                for i in xrange(arr_len):
                    arr_value = arr[i]
                    key_with_signal = arr_value
                    key = tool.msz_str_2_time(key_with_signal[1:len(key_with_signal) - 1])
                    block = line_irc[len(key_with_signal) * arr_len:len(line_irc)]
                    self._blocks[key] = block

    def getBlock(self, time):
        """根据时间获取当前歌词"""
        if time in self._blocks:
            return self._blocks[time]
        else:
            find = False
            while not find:
                time -= 1
                if time < 0:
                    return None
                if time in self._blocks:
                    return self._blocks[time]

    def clear(self):
        self._blocks = {}